import type { Router } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useToast } from 'vue-toastification'
import { PermissionUtils } from '../utils/permissions'

export function setupRouterGuards(router: Router) {
  const toast = useToast()

  // 全局前置守卫
  router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore()
    
    // 设置页面标题
    if (to.meta.title) {
      document.title = to.meta.title
    }

    // 检查是否需要认证
    if (to.meta.requiresAuth) {
      if (!authStore.isAuthenticated) {
        toast.error('Please login to access this page')
        next({ name: 'Login', query: { redirect: to.fullPath } })
        return
      }

      // 检查用户是否激活
      if (!PermissionUtils.isActiveUser(authStore.user)) {
        toast.error('Your account has been deactivated')
        authStore.logout()
        next({ name: 'Login' })
        return
      }

      // 检查是否需要管理员权限
      if (to.meta.requiresAdmin && !PermissionUtils.hasAdminAccess(authStore.user)) {
        toast.error('Admin access required')
        next({ name: 'Dashboard' })
        return
      }

      // 使用权限工具检查路由访问权限
      if (to.name && !PermissionUtils.canAccessRoute(authStore.user, to.name.toString())) {
        toast.error('You do not have permission to access this page')
        next({ name: 'Dashboard' })
        return
      }
    }

    // 如果已登录用户访问登录页，重定向到仪表板
    if (to.name === 'Login' && authStore.isAuthenticated) {
      next({ name: 'Dashboard' })
      return
    }

    next()
  })

  // 全局后置钩子
  router.afterEach((to, from) => {
    // 可以在这里添加页面访问统计等逻辑
    console.log(`Navigated from ${from.name} to ${to.name}`)
  })
}
